use std::borrow::Cow;
use std::collections::HashMap;


#[derive(Debug, Default)]
pub struct Cmd {
    pub name: String,
    pub args: HashMap<DataKey, Data>,
}

impl Cmd{


    /**
    parse_args 函数用于解析命令行参数，并将它们转换为一个 HashMap<DataKey, Data>。
    它能够处理长参数和非长参数，并根据参数的格式生成相应的键和值
    */
    pub fn parse_args(
        words: impl Iterator<Item = String>,
        obase: bool,
    ) -> Result<HashMap<DataKey, Data>> {
        let mut i = 0i64;
        words
            .into_iter()
            .map(|word| {
                let Some(arg) = word.strip_prefix("--") else {
                    i += 1;
                    return Ok((DataKey::Integer(i - obase as i64), Data::String(word)));
                };

                let mut parts = arg.splitn(2, '=');
                let Some(key) = parts.next().map(|s| s.to_owned()) else {
                    bail!("invalid argument: {arg}");
                };

                let val = if let Some(val) = parts.next() {
                    Data::String(val.to_owned())
                } else {
                    Data::Boolean(true)
                };

                Ok((DataKey::String(Cow::Owned(key)), val))
            })
            .collect()
    }
}